package com.sy.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.sy.bean.JwtOperation;
import com.sy.constant.AppConstant;
import com.sy.dto.*;
import com.sy.entity.*;
import com.sy.entity.Level;
import com.sy.exception.ShopSystemException;
import com.sy.mapper.*;
import com.sy.mapper.LevelMapper;
import com.sy.mapper.UserMapper;
import com.sy.service.GoodService;
import com.sy.service.UserService;
import com.sy.utils.SmsUtils;
import com.sy.utils.ValidateCodeUtils;
import com.sy.vo.MemberParams;
import com.sy.vo.ReceiverParam;
import com.sy.vo.UpdateReveiverParam;
import io.jsonwebtoken.Claims;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.*;


/**
 * @Description:用户相关业务层实现类
 * @Author: 董星奇
 * @Date:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private LevelMapper levelMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private SafeQuestionMapper safeQuestionMapper;

    @Autowired
    private UserQuestionMapper userQuestionMapper;

    @Autowired
    private JwtOperation jwtOperation;


    @Autowired
    private ProvinceMapper provinceMapper;

    @Autowired
    private CityMapper cityMapper;

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private CollectionMapper collectionMapper;

    @Autowired
    private EvaluateMapper evaluateMapper;

    @Autowired
    private HistoryMapper historyMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderProductRefMapper orderProductRefMapper;

    @Autowired
    private FlavorMapper flavorMapper;

    @Autowired
    private PackagingMapper packagingMapper;

    /**
     * @param email          邮箱
     * @param userName       用户名
     * @param emailpassword  输入密码
     * @param passwordRepeat 确认密码
     * @return result
     * @Author 董星奇
     */
    @Transactional
    @Override
    public Result registByEmail(String email, String userName, String emailpassword, String passwordRepeat) {
        Result result = new Result();
        try {
            if (StringUtils.isBlank(email)) {
                throw new ShopSystemException("邮箱不能为空");
            }
            if (StringUtils.isBlank(userName)) {
                throw new ShopSystemException("用户名不能为空");
            }
            if (StringUtils.isBlank(emailpassword)) {
                throw new ShopSystemException("输入密码不能为空");
            }
            if (StringUtils.isBlank(passwordRepeat)) {
                throw new ShopSystemException("确认密码不能为空");
            }
            if (!email.matches(AppConstant.EMAIL_REGEXP)) {
                throw new ShopSystemException("请输入正确的邮箱格式");
            }
            if (!StringUtils.equals(emailpassword, passwordRepeat)) {
                throw new ShopSystemException("两次密码输入必须一致");
            }
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("email", email);
            User user = userMapper.selectOne(userQueryWrapper);
            if (null != user) {
                throw new ShopSystemException("该邮箱已被注册");
            }
            QueryWrapper<User> userQueryWrapper1 = new QueryWrapper<>();
            userQueryWrapper1.eq("userName", userName);
            User user1 = userMapper.selectOne(userQueryWrapper1);
            if (null != user1) {
                throw new ShopSystemException("该用户名已存在了");
            }
            String nickname = AppConstant.PRE_NICKNAME + RandomStringUtils.randomAlphabetic(8);
            User user2 = new User();
            user2.setUserName(userName);
            user2.setEmail(email);
            user2.setPwd(emailpassword);
            user2.setNickName(nickname);
            user2.setStatus(String.valueOf(AppConstant.USER_DEFAULT_STATUS));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            user2.setJoinTime(sdf.format(new Date()));
            user2.setAccountSecurity(AppConstant.USER_DEFAULT_SAFE_SCORE);
            user2.setLevel(String.valueOf(AppConstant.USER_DEFAULT_LEVEL));
            user2.setLatestConsumption(BigDecimal.valueOf(AppConstant.USER_DEFAULT_LATESTCONSUMPTION));
            user2.setIntegral(AppConstant.USER_DEFAULT_INTEGRAL);
            user2.setViewNum(AppConstant.USER_DEFAULT_VIEWNUM);
            user2.setShoppingRadio(AppConstant.USER_DEFAULT_SHOPPINGRADIO);
            user2.setBalance(AppConstant.USER_DEFAULT_BALANCE);
            user2.setSignature(AppConstant.USER_DEFAULT_SIGNATURE);
            Integer i = userMapper.insert(user2);
            if (i == 0) {
                throw new ShopSystemException("新增用户失败");
            }
            result.setCode(201);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 手机注册时要发送的验证码
     *
     * @param phone 手机号码
     * @Author 董星奇
     */
    @Override
    public Result sendMessage(String phone) {
        Result result = new Result();
        try {
            if (StringUtils.isBlank(phone)) {
                throw new ShopSystemException("要注册是手机号码不能为空");
            }
            if (!phone.matches(AppConstant.PHONE_REGEXP)) {
                throw new ShopSystemException("请输入正确的手机格式");
            }
            String code = ValidateCodeUtils.getRandomStr(AppConstant.SHORT_MESSAGE_VALIDATE_CODE_LENGTH);
            SmsUtils.sendMail(phone, code);
            result.setCode(200);
            result.setData(code);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 手机号码注册
     *
     * @param phone               手机号码
     * @param code                输入的验证码
     * @param phonepassword       输入的密码
     * @param phonepasswordRepeat 确认密码
     * @param codetoken           手机收到的验证码
     * @Author 董星奇
     */
    @Transactional
    @Override
    public Result registByPhone(String phone, String code, String phonepassword, String phonepasswordRepeat, String userName, String codetoken) {
        Result result = new Result();
        try {
            if (StringUtils.isBlank(phone)) {
                throw new ShopSystemException("输入的手机号码不能为空");
            }
            if (!phone.matches(AppConstant.PHONE_REGEXP)) {
                throw new ShopSystemException("请输入正确的手机号码格式");
            }
            if (StringUtils.isBlank(code)) {
                throw new ShopSystemException("输入的验证码不能为空");
            }
            if (StringUtils.isBlank(phonepassword)) {
                throw new ShopSystemException("输入密码不能为空");
            }
            if (StringUtils.isBlank(phonepasswordRepeat)) {
                throw new ShopSystemException("输入确认密码不能为空");
            }
            if (StringUtils.isBlank(userName)) {
                throw new ShopSystemException("输入用户名不能为空");
            }
            if (!StringUtils.equals(phonepassword, phonepasswordRepeat)) {
                throw new ShopSystemException("两次密码输入必须一致");
            }
            if (!StringUtils.equals(code, codetoken)) {
                throw new ShopSystemException("验证码不正确");
            }
            QueryWrapper<User> userQueryWrapper1 = new QueryWrapper<>();
            userQueryWrapper1.eq("phone", phone);
            User user = userMapper.selectOne(userQueryWrapper1);
            if (null != user) {
                throw new ShopSystemException("该手机号码已经被注册了");
            }
            QueryWrapper<User> userQueryWrapper2 = new QueryWrapper<>();
            userQueryWrapper2.eq("userName", userName);
            User user1 = userMapper.selectOne(userQueryWrapper2);
            if (null != user1) {
                throw new ShopSystemException("该用户名已存在了");
            }
            String nickname = AppConstant.PRE_NICKNAME + RandomStringUtils.randomAlphabetic(8);
            User user2 = new User();
            user2.setUserName(userName);
            user2.setPhone(phone);
            user2.setPwd(phonepassword);
            user2.setNickName(nickname);
            user2.setAccountSecurity(AppConstant.USER_DEFAULT_SAFE_SCORE);
            user2.setStatus(String.valueOf(AppConstant.USER_DEFAULT_ADDRESS_STATUS));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            user2.setJoinTime(sdf.format(new Date()));
            user2.setLevel(String.valueOf(AppConstant.USER_DEFAULT_LEVEL));
            user2.setLatestConsumption(BigDecimal.valueOf(AppConstant.USER_DEFAULT_LATESTCONSUMPTION));
            user2.setIntegral(AppConstant.USER_DEFAULT_INTEGRAL);
            user2.setViewNum(AppConstant.USER_DEFAULT_VIEWNUM);
            user2.setShoppingRadio(AppConstant.USER_DEFAULT_SHOPPINGRADIO);
            user2.setBalance(AppConstant.USER_DEFAULT_BALANCE);
            user2.setSignature(AppConstant.USER_DEFAULT_SIGNATURE);
            Integer i = userMapper.insert(user2);
            if (i == 0) {
                throw new ShopSystemException("新增用户失败");
            }
            result.setCode(201);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 用户登录
     *
     * @param message  登录账号
     * @param password 密码
     * @Author 董星奇
     */
    @Transactional
    @Override
    public Result login(String message, String password) {
        Result result = new Result();
        try {
            if (StringUtils.isBlank(message)) {
                throw new ShopSystemException("登录账号不能为空");
            }
            if (StringUtils.isBlank(password)) {
                throw new ShopSystemException("登录密码不能为空");
            }
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("userName", message);
            QueryWrapper<User> userQueryWrapper1 = new QueryWrapper<>();
            userQueryWrapper1.eq("phone", message);
            QueryWrapper<User> userQueryWrapper2 = new QueryWrapper<>();
            userQueryWrapper2.eq("email", message);
            //名字
            if (userMapper.selectList(userQueryWrapper).size() > 0) {
                User user = userMapper.selectOne(userQueryWrapper);
                if (!password.equals(user.getPwd())) {
                    throw new ShopSystemException("用户名或密码错误");
                }
                //创建jwt
                String token = jwtOperation.createJwt(user);
                result.setCode(200);
                //登录成功返回用户基本信息以及Token
                Map<String, Object> userdata = new LinkedHashMap<String, Object>() {{
                    put("token", token);
                    put("userInfo", user);
                }};
                result.setData(userdata);
            }
            //电话
            else if (userMapper.selectList(userQueryWrapper1).size() > 0) {
                User user = userMapper.selectOne(userQueryWrapper1);
                if (!password.equals(user.getPwd())) {
                    throw new ShopSystemException("用户名或密码错误");
                }
                //创建jwt
                String token = jwtOperation.createJwt(user);
                result.setCode(200);
                //登录成功返回用户基本信息以及Token
                Map<String, Object> userdata = new LinkedHashMap<String, Object>() {{
                    put("token", token);
                    put("userInfo", user);
                }};
                result.setData(userdata);
            }
            //邮箱
            else if (userMapper.selectList(userQueryWrapper2).size() > 0) {
                User user = userMapper.selectOne(userQueryWrapper2);
                if (!password.equals(user.getPwd())) {
                    throw new ShopSystemException("用户名或密码错误");
                }
                //创建jwt
                String token = jwtOperation.createJwt(user);
                result.setCode(200);
                //登录成功返回用户基本信息以及Token
                Map<String, Object> userdata = new LinkedHashMap<String, Object>() {{
                    put("token", token);
                    put("userInfo", user);
                }};
                result.setData(userdata);
            } else {
                throw new ShopSystemException("该账号不存在");
            }
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 获取当前登录的用户
     *
     * @param token token包含了用户信息
     * @Author 董星奇
     */
    @Override
    public User LoginUser(String token) {
        Result result = new Result();
        User loginUser = new User();
        try {
            if (StringUtils.isBlank(token)) {
                throw new ShopSystemException("没有携带Token信息");
            }
            //获取Claims
            Claims claims = jwtOperation.parseJwt(token);
            Object userClaim = claims.get("user");
            if (null == claims || null == userClaim) {
                throw new ShopSystemException("无效的Token");
            }
            //获取用户信息
            User user = JSON.parseObject(String.valueOf(claims.get("user")), User.class);
            String username = user.getUserName();
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("userName", username);
            loginUser = userMapper.selectOne(userQueryWrapper);
            System.out.println(loginUser);
            loginUser.setPwd(null);
            System.out.println(loginUser);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            if (e instanceof ShopSystemException) {
                result.setCode(401);
                result.setError("登录信息已过期");
            }
            if (e instanceof ShopSystemException) {
                result.setCode(401);
                result.setError(e.getMessage());
            } else {
                result.setCode(500);
                result.setError("服务器异常");
            }
        }
        return loginUser;
    }

    /**
     * 忘记密码
     *
     * @param forgetMessage 手机号码或是邮箱
     * @Author: 董星奇
     */
    @Transactional
    @Override
    public Result forgetPassword(String forgetMessage) {
        Result result = new Result();
        try {
            if (StringUtils.isBlank(forgetMessage)) {
                throw new ShopSystemException("输入邮箱或手机号码不要为空");
            }
            QueryWrapper<User> userQueryWrapper1 = new QueryWrapper<>();
            userQueryWrapper1.eq("phone", forgetMessage);
            QueryWrapper<User> userQueryWrapper2 = new QueryWrapper<>();
            userQueryWrapper2.eq("email", forgetMessage);
            //邮箱
            if (userMapper.selectList(userQueryWrapper1).size() > 0) {
                User user = userMapper.selectOne(userQueryWrapper1);
                result.setData(user);
                result.setCode(200);
            }
            //手机号码
            else if (userMapper.selectList(userQueryWrapper2).size() > 0) {
                User user = userMapper.selectOne(userQueryWrapper2);
                result.setCode(200);
                result.setData(user);
            } else {
                throw new ShopSystemException("该用户不存在,请你确认输入内容是否正确");
            }
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 个人中心资料修改
     *
     * @param nickname 昵称
     * @param name     名字
     * @param sex      性别
     * @param birthday 生日
     * @param phone    手机号码
     * @param email    邮箱
     * @Author: 董星奇
     */
    @Transactional
    @Override
    public Result updateUserInfo(Integer id, String nickname, String name, Integer sex, String birthday, String phone, String email) {
        Result result = new Result();
        try {
            if (null == id) {
                throw new ShopSystemException("id不能为空");
            }
            if (StringUtils.isBlank(nickname)) {
                throw new ShopSystemException("昵称不能为空");
            }
            if (StringUtils.isBlank(name)) {
                throw new ShopSystemException("名字不能为空");
            }
            if (null == sex) {
                throw new ShopSystemException("性别不能为空");
            }
            if (StringUtils.isBlank(birthday)) {
                throw new ShopSystemException("生日不能为空");
            }
            if (StringUtils.isBlank(phone)) {
                throw new ShopSystemException("手机号码不能为空");
            }
            if (StringUtils.isBlank(email)) {
                throw new ShopSystemException("邮箱不能为空");
            }
            if (!phone.matches(AppConstant.PHONE_REGEXP)) {
                throw new ShopSystemException("请输入正确的手机号码格式");
            }
            if (!email.matches(AppConstant.EMAIL_REGEXP)) {
                throw new ShopSystemException("请输入正确的邮箱格式");
            }
            User user = userMapper.selectById(id);
            if (null == user) {
                throw new ShopSystemException("该用户不存在");
            }
            QueryWrapper<User> userQueryWrapper1 = new QueryWrapper<>();
            userQueryWrapper1.eq("phone", phone);
            User user1 = userMapper.selectOne(userQueryWrapper1);
            if (null != user1) {
                if (!id.equals(user1.getId())) {
                    throw new ShopSystemException("手机号码已被其他用户注册了");
                }
            }
            QueryWrapper<User> userQueryWrapper2 = new QueryWrapper<>();
            userQueryWrapper2.eq("email", email);
            User user2 = userMapper.selectOne(userQueryWrapper2);
            if (null != user2) {
                if (!id.equals(user2.getId())) {
                    throw new ShopSystemException("邮箱已被其他用户注册了");
                }
            }

            Integer lastScore = user.getAccountSecurity() + AppConstant.ACCOUNT_SECURITY;
            User user3 = new User();
            user3.setId(id);
            user3.setNickName(nickname);
            user3.setName(name);
            user3.setSex(sex);
            user3.setBirthday(java.sql.Date.valueOf(birthday));
            user3.setPhone(phone);
            user3.setEmail(email);
            user3.setAccountSecurity(lastScore);
            Integer i = userMapper.updateById(user3);
            if (i == 0) {
                throw new ShopSystemException("更新用户失败");
            }
            result.setCode(200);
            result.setData(user3);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }


    /**
     * 获取会员信息
     *
     * @return
     * @Author 孙玮立
     */
    @Override
    public Result getUsers() {
        Result result = new Result();
        try {
            List<User> users = userMapper.selectList(null);
            result.setData(users);
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 获取符合查询条件的会员信息
     *
     * @return
     * @Author 孙玮立
     */
    @Override
    public Result getUsersByKeyWord(String keyWord) {
        Result result = new Result();
        try {
            List<User> users = new ArrayList<>();
            if (StringUtils.isBlank(keyWord)) {
                users = userMapper.selectList(null);
            } else {
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("userName", keyWord);
                users = userMapper.selectList(userQueryWrapper);
            }
            result.setData(users);
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    @Override
    public Result getUsersByKeyWordAndTime(String keyWord, String time) {
        Result result = new Result();
        try {
            List<User> users = new ArrayList<>();
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            if (!StringUtils.isBlank(keyWord)) {
                if (keyWord.matches(AppConstant.EMAIL_REGEXP)) {
                    userQueryWrapper.eq("email", keyWord);
                } else if (keyWord.matches(AppConstant.PHONE_REGEXP)) {
                    userQueryWrapper.eq("phone", keyWord);
                } else {
                    userQueryWrapper.eq("userName", keyWord);
                }
            }
            if (!StringUtils.isBlank(time)){
                userQueryWrapper.eq("joinTime",time);
            }
            users = userMapper.selectList(userQueryWrapper);
            result.setData(users);
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }


    /**
     * 获取会员等级信息
     *
     * @return
     * @Author 孙玮立
     */
    @Override
    public Result getLevelCount() {
        Result result = new Result();
        try {
            List<LevelInfo> levelInfos = new ArrayList<>();
            List<Level> levels = levelMapper.selectList(null);
            Integer total = userMapper.selectCount(null);
            LevelInfo AlllevelInfo = new LevelInfo();
            AlllevelInfo.setId(0);
            AlllevelInfo.setLevel("全部");
            AlllevelInfo.setCount(total);
            levelInfos.add(AlllevelInfo);
            for (Level level : levels) {
                LevelInfo levelInfo = new LevelInfo();
                Integer levelId = level.getId();
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("level", levelId);
                Integer count = userMapper.selectCount(queryWrapper);
                levelInfo.setId(level.getId());
                levelInfo.setLevel(level.getLevel());
                levelInfo.setCount(count);
                levelInfos.add(levelInfo);
            }
            result.setData(levelInfos);
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 删除会员信息
     *
     * @param ids 会员编号
     * @return
     * @Author 孙玮立
     */
    @Override
    public Result deleteUsers(String ids) {
        Result result = new Result();
        try {
            if (StringUtils.isBlank(ids)) {
                throw new ShopSystemException("请选择用户进行删除");
            }
            List<String> list = Arrays.asList(ids.split(","));
            for (String id : list) {
                userMapper.deleteById(id);
            }
            result.setData(getLevelCount());
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @param id
     * @param status 启用状态
     * @return
     * @Author 孙玮立
     * 更改用户账户状态
     */
    @Override
    public Result uploadUser(String id, String status) {
        Result result = new Result();
        try {
            User user = userMapper.selectById(id);
            user.setStatus(status);
            userMapper.updateById(user);
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 添加会员信息
     *
     * @param memberParams 会员信息
     * @return
     * @Author 孙玮立
     */
    @Override
    public Result addUser(MemberParams memberParams) {
        Result result = new Result();
        try {
            if (StringUtils.isBlank(memberParams.getEmail())) {
                throw new ShopSystemException("邮箱不能为空");
            }
            if (StringUtils.isBlank(memberParams.getUserName())) {
                throw new ShopSystemException("用户名不能为空");
            }
            if (StringUtils.isBlank(memberParams.getName())) {
                throw new ShopSystemException("真实姓名不能为空");
            }
            if (StringUtils.isBlank(memberParams.getAddress())) {
                throw new ShopSystemException("家庭住址不能为空");
            }
            if (null == memberParams.getSex()) {
                throw new ShopSystemException("性别不能为空");
            }
            if (null == memberParams.getStatus()) {
                throw new ShopSystemException("启用状态不能为空");
            }
            if (!memberParams.getEmail().matches(AppConstant.EMAIL_REGEXP)) {
                throw new ShopSystemException("请输入正确的邮箱格式");
            }
            if (StringUtils.isBlank(memberParams.getPhone())) {
                throw new ShopSystemException("手机号码不能为空");
            }
            if (!memberParams.getPhone().matches(AppConstant.PHONE_REGEXP)) {
                throw new ShopSystemException("请输入正确的手机格式");
            }
            QueryWrapper<User> phoneUserQueryWrapper1 = new QueryWrapper<>();
            phoneUserQueryWrapper1.eq("phone", memberParams.getPhone());
            User phoneUser = userMapper.selectOne(phoneUserQueryWrapper1);
            if (null != phoneUser) {
                throw new ShopSystemException("该手机号码已经被注册了");
            }

            QueryWrapper<User> emailUserQueryWrapper = new QueryWrapper<>();
            emailUserQueryWrapper.eq("email", memberParams.getEmail());
            User emailUser = userMapper.selectOne(emailUserQueryWrapper);
            if (null != emailUser) {
                throw new ShopSystemException("该邮箱已被注册");
            }
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("userName", memberParams.getUserName());
            User user = userMapper.selectOne(userQueryWrapper);
            if (null != user) {
                throw new ShopSystemException("该用户名已存在了");
            }
            String nickname = AppConstant.PRE_NICKNAME + RandomStringUtils.randomAlphabetic(8);
            User newUser = new User();
            newUser.setUserName(memberParams.getUserName());
            newUser.setEmail(memberParams.getEmail());
            newUser.setStatus(memberParams.getStatus());
            newUser.setPhone(memberParams.getPhone());
            newUser.setSex(memberParams.getSex());
            newUser.setName(memberParams.getName());
            newUser.setAddress(memberParams.getAddress());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date data = new Date();
            newUser.setJoinTime(sdf.format(data));
            newUser.setLevel("1");
            newUser.setPwd("123456");
            newUser.setNickName(nickname);
            newUser.setStatus("1");
            Integer i = userMapper.insert(newUser);
            if (i == 0) {
                throw new ShopSystemException("新增用户失败");
            }
            result.setCode(201);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 获取会员信息
     *
     * @param id 会员编号
     * @return
     * @Author 孙玮立
     */
    @Override
    public User getUser(String id) {
        try {
            User user = userMapper.selectById(id);
            return user;
        } catch (ShopSystemException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 修改会员信息
     *
     * @param id           会员编号
     * @param memberParams 会员信息
     * @return
     * @Author 孙玮立
     */
    @Override
    public Result uploadUserById(String id, MemberParams memberParams) {
        Result result = new Result();
        try {
            User user = userMapper.selectById(id);
            user.setName("");
            user.setAddress("");
            user.setPhone("");
            user.setEmail("");
            userMapper.updateById(user);
            if (StringUtils.isBlank(memberParams.getEmail())) {
                throw new ShopSystemException("邮箱不能为空");
            }
            if (StringUtils.isBlank(memberParams.getName())) {
                throw new ShopSystemException("真实姓名不能为空");
            }
            if (StringUtils.isBlank(memberParams.getAddress())) {
                throw new ShopSystemException("家庭住址不能为空");
            }
            if (null == memberParams.getSex()) {
                throw new ShopSystemException("性别不能为空");
            }
            if (null == memberParams.getStatus()) {
                throw new ShopSystemException("启用状态不能为空");
            }
            if (!memberParams.getEmail().matches(AppConstant.EMAIL_REGEXP)) {
                throw new ShopSystemException("请输入正确的邮箱格式");
            }
            if (StringUtils.isBlank(memberParams.getPhone())) {
                throw new ShopSystemException("手机号码不能为空");
            }
            if (!memberParams.getPhone().matches(AppConstant.PHONE_REGEXP)) {
                throw new ShopSystemException("请输入正确的手机格式");
            }

            QueryWrapper<User> phoneUserQueryWrapper1 = new QueryWrapper<>();
            phoneUserQueryWrapper1.eq("phone", memberParams.getPhone());
            User phoneUser = userMapper.selectOne(phoneUserQueryWrapper1);
            if (null != phoneUser) {
                throw new ShopSystemException("该手机号码已经被注册了");
            }

            QueryWrapper<User> emailUserQueryWrapper = new QueryWrapper<>();
            emailUserQueryWrapper.eq("email", memberParams.getEmail());
            User emailUser = userMapper.selectOne(emailUserQueryWrapper);
            if (null != emailUser) {
                throw new ShopSystemException("该邮箱已被注册");
            }
            user.setEmail(memberParams.getEmail());
            user.setPhone(memberParams.getPhone());
            user.setAddress(memberParams.getAddress());
            user.setName(memberParams.getName());
            user.setSex(memberParams.getSex());
            user.setStatus(memberParams.getStatus());
            userMapper.updateById(user);
            result.setCode(201);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 清除会员购物记录
     *
     * @param ids 会员编号
     * @return
     * @Author 孙玮立
     */
    @Override
    public Result clearRecords(String ids) {
        Result result = new Result();
        try {
            if (StringUtils.isBlank(ids)) {
                throw new ShopSystemException("请选择用户进行清除");
            }
            List<String> list = Arrays.asList(ids.split(","));
            for (String id : list) {
                User user = userMapper.selectById(id);
                if (null == user) {
                    throw new ShopSystemException("该用户不存在");
                }
                user.setIntegral("0");
                user.setViewNum(0);
                user.setShoppingRadio("0");
                userMapper.updateById(user);
            }
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }


    /**
     * 修改用户密码
     *
     * @param id         当前用户id
     * @param oldPwd     原密码
     * @param newPwd     新密码
     * @param confirmPwd 确认密码
     * @Author: 董星奇
     */
    @Transactional
    @Override
    public Result updateUserPwd(Integer id, String oldPwd, String newPwd, String confirmPwd) {
        Result result = new Result();
        try {
            if (null == id) {
                throw new ShopSystemException("id不能为空");
            }
            if (StringUtils.isBlank(oldPwd)) {
                throw new ShopSystemException("原密码不能为空");
            }
            if (StringUtils.isBlank(newPwd)) {
                throw new ShopSystemException("新密码不能为空");
            }
            if (StringUtils.isBlank(confirmPwd)) {
                throw new ShopSystemException("新密码不能为空");
            }
            if (!StringUtils.equals(newPwd, confirmPwd)) {
                throw new ShopSystemException("新密码与确认密码必须输入一致");
            }
            User user = userMapper.selectById(id);
            if (!StringUtils.equals(oldPwd, user.getPwd())) {
                throw new ShopSystemException("请输入正确的原密码");
            }
            User user1 = new User();
            user1.setId(id);
            user1.setPwd(newPwd);
            Integer i = userMapper.updateById(user1);
            if (i == 0) {
                throw new ShopSystemException("修改密码失败");
            }
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 设置支付密码
     *
     * @param id            当前用户id
     * @param code          输入的验证码
     * @param payPwd        支付密码
     * @param confirmPayPwd 确认支付密码
     * @param phonecode     手机收到的验证码
     * @Author: 董星奇
     */
    @Transactional
    @Override
    public Result setUPayPwd(Integer id, String code, String payPwd, String confirmPayPwd, String phonecode) {
        Result result = new Result();
        try {
            if (null == id) {
                throw new ShopSystemException("id不能为空");
            }
            if (StringUtils.isBlank(code)) {
                throw new ShopSystemException("输入的验证码不能为空");
            }
            if (StringUtils.isBlank(payPwd)) {
                throw new ShopSystemException("支付密码不能为空");
            }
            if (StringUtils.isBlank(confirmPayPwd)) {
                throw new ShopSystemException("确认支付密码不能为空");
            }
            if (StringUtils.isBlank(phonecode)) {
                throw new ShopSystemException("手机收到的验证码不能为空");
            }
            if (!StringUtils.equals(code, phonecode)) {
                throw new ShopSystemException("验证码不正确");
            }
            if (!StringUtils.equals(payPwd, confirmPayPwd)) {
                throw new ShopSystemException("两次密码输入必须相等");
            }
            if (!payPwd.matches(AppConstant.PAYPWD_REGEXP)) {
                throw new ShopSystemException("支付密码必须是6位数字");
            }
            if (!confirmPayPwd.matches(AppConstant.PAYPWD_REGEXP)) {
                throw new ShopSystemException("确认支付密码也必须是6位数字");
            }
            User user = userMapper.selectById(id);
            if (null == user) {
                throw new ShopSystemException("该用户不存在");
            }
            if (StringUtils.equals(payPwd, user.getPayPwd())) {
                throw new ShopSystemException("新密码与原密码不要相同");
            }
            Integer score = user.getAccountSecurity() + AppConstant.USER_SCORE;
            User user1 = new User();
            user1.setId(id);
            user1.setAccountSecurity(score);
            user1.setPayPwd(payPwd);
            Integer i = userMapper.updateById(user1);
            if (i == 0) {
                throw new ShopSystemException("设置支付密码失败");
            }
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 更改手机号码
     *
     * @param id             当前用户id
     * @param phone          旧的手机号码
     * @param oldcode        旧手机输入的验证码
     * @param bindPhone      新绑定的手机
     * @param code           新手机输入的验证码
     * @param oldSessionCode 旧手机收到的验证码存在session中
     * @param newSessionCode 新手机收到的验证码存在session中
     * @Author: 董星奇
     */
    @Transactional
    @Override
    public Result updatePhone(Integer id, String phone, String oldcode, String bindPhone, String code, String oldSessionCode, String newSessionCode) {
        Result result = new Result();
        try {
            if (null == id) {
                throw new ShopSystemException("id不能为空");
            }
            if (StringUtils.isBlank(phone)) {
                throw new ShopSystemException("原来的手机号码不能为空");
            }
            if (StringUtils.isBlank(oldcode)) {
                throw new ShopSystemException("输入的验证码不能为空");
            }
            if (StringUtils.isBlank(bindPhone)) {
                throw new ShopSystemException("新绑定的手机号码不能为空");
            }
            if (StringUtils.isBlank(code)) {
                throw new ShopSystemException("输入的验证码不能为空");
            }
            if (StringUtils.isBlank(oldSessionCode)) {
                throw new ShopSystemException("原来的手机号码未收到验证码");
            }
            if (StringUtils.isBlank(newSessionCode)) {
                throw new ShopSystemException("新的手机号码未收到验证码");
            }
            if (!StringUtils.equals(oldcode, oldSessionCode)) {
                throw new ShopSystemException("原来的手机号码输入验证码错误");
            }
            if (!StringUtils.equals(code, newSessionCode)) {
                throw new ShopSystemException("新的手机号码输入验证码错误");
            }
            User user1 = userMapper.selectById(id);
            if (null == user1) {
                throw new ShopSystemException("该用户不存在，可能不小心被删除了");
            }
            QueryWrapper<User> userQueryWrapper1 = new QueryWrapper<>();
            userQueryWrapper1.eq("phone", phone);
            User user2 = userMapper.selectOne(userQueryWrapper1);
            if (null == user2) {
                throw new ShopSystemException("原来的手机号码不存在");
            }
            QueryWrapper<User> userQueryWrapper2 = new QueryWrapper<>();
            userQueryWrapper2.eq("phone", bindPhone);
            User user3 = userMapper.selectOne(userQueryWrapper2);
            if (null != user3) {
                throw new ShopSystemException("你输入的新绑定的手机号已被其他用户占用了");
            }
            User user = new User();
            user.setId(id);
            user.setPhone(bindPhone);
            Integer i = userMapper.updateById(user);
            if (i == 0) {
                throw new ShopSystemException("修改绑定手机号码失败");
            }
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 绑定邮箱操作
     *
     * @param id    当前用户的id
     * @param email 邮箱
     * @param code  输入的验证码
     * @Author: 董星奇
     */
    @Transactional
    @Override
    public Result bindEmail(Integer id, String email, String code, String sessionCode) {
        Result result = new Result();
        try {
            if (null == id) {
                throw new ShopSystemException("id不能为空");
            }
            if (StringUtils.isBlank(email)) {
                throw new ShopSystemException("邮箱不能为空");
            }
            if (StringUtils.isBlank(code)) {
                throw new ShopSystemException("输入验证码不能为空");
            }
            if (StringUtils.isBlank(sessionCode)) {
                throw new ShopSystemException("生成的验证码不能为空");
            }
            if (!StringUtils.equals(code, sessionCode)) {
                throw new ShopSystemException("验证码不正确");
            }

            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("id", id).eq("email", email);
            User user1 = userMapper.selectOne(userQueryWrapper);
            if (null != user1) {
                throw new ShopSystemException("你已经绑定了该邮箱");
            }
            QueryWrapper<User> userQueryWrapper1 = new QueryWrapper<>();
            userQueryWrapper1.eq("email", email);
            User user2 = userMapper.selectOne(userQueryWrapper1);
            if (null != user2) {
                throw new ShopSystemException("该邮箱已被其他用户绑定了");
            }
            QueryWrapper<User> userQueryWrapper2 = new QueryWrapper<>();
            userQueryWrapper2.eq("id", id);
            User user3 = userMapper.selectOne(userQueryWrapper2);
            Integer score = user3.getAccountSecurity() + AppConstant.USER_SCORE;
            User user = new User();

            user.setAccountSecurity(score);
            user.setId(id);
            user.setEmail(email);
            Integer i = userMapper.updateById(user);
            if (i == 0) {
                throw new ShopSystemException("绑定邮箱失败");
            }
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 实名认证
     *
     * @param id    当前用户id
     * @param phone 手机号码
     * @param name  真实姓名
     * @param card  身份证号码
     * @Author: 董星奇
     */
    @Transactional
    @Override
    public Result realName(Integer id, String phone, String name, String card) {
        Result result = new Result();
        try {
            if (null == id) {
                throw new ShopSystemException("id不能为空");
            }
            if (StringUtils.isBlank(phone)) {
                throw new ShopSystemException("手机号码不能为空");
            }
            if (StringUtils.isBlank(name)) {
                throw new ShopSystemException("真实姓名不能为空");
            }
            if (StringUtils.isBlank(card)) {
                throw new ShopSystemException("身份证号码不能为空");
            }
            if (!phone.matches(AppConstant.PHONE_REGEXP)) {
                throw new ShopSystemException("手机号码格式不合法");
            }
            if (!card.matches(AppConstant.ID_CARD)) {
                throw new ShopSystemException("请输入合法的身份证格式");
            }
            User user = userMapper.selectById(id);
            if (null == user) {
                throw new ShopSystemException("该用户可能不存在了");
            }
            QueryWrapper<User> userQueryWrapper1 = new QueryWrapper<>();
            userQueryWrapper1.eq("id", id).eq("card", card);
            User user2 = userMapper.selectOne(userQueryWrapper1);
            if (null != user2) {
                throw new ShopSystemException("你已经实名认证过了");
            }
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("card", card);
            User user3 = userMapper.selectOne(userQueryWrapper);
            if (null != user3) {
                throw new ShopSystemException("该身份证号已被实名认证了");
            }
            Integer score = user.getAccountSecurity() + AppConstant.USER_SCORE;
            User user1 = new User();
            user1.setId(id);
            user1.setPhone(phone);
            user1.setName(name);
            user1.setCard(card);
            user1.setAccountSecurity(score);
            Integer i = userMapper.updateById(user1);
            if (i == 0) {
                throw new ShopSystemException("实名认证失败");
            }
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 用户填写安全问题
     *
     * @param id          当前用户id
     * @param questionId1 问题1id
     * @param answer1     问题1答案
     * @param questionId2 问题2id
     * @param answer2     问题2答案
     * @Author: 董星奇
     */
    @Transactional
    @Override
    public Result addSafeQuestions(Integer id, Integer questionId1, String answer1, Integer questionId2, String answer2) {
        Result result = new Result();
        try {
            if (null == id) {
                throw new ShopSystemException("id不能为空");
            }
            if (null == questionId1) {
                throw new ShopSystemException("问题一id不能为空");
            }
            if (StringUtils.isBlank(answer1)) {
                throw new ShopSystemException("答案一不能为空");
            }
            if (null == questionId2) {
                throw new ShopSystemException("问题一id不能为空");
            }
            if (StringUtils.isBlank(answer2)) {
                throw new ShopSystemException("答案二不能为空");
            }
            if (questionId1.equals(questionId2)) {
                throw new ShopSystemException("请不要设置相同的问题");
            }
            User user1 = userMapper.selectById(id);
            if (null == user1) {
                throw new ShopSystemException("该用户可能不存在了");
            }
            SafeQuestion safeQuestion1 = safeQuestionMapper.selectById(questionId1);
            if (null == safeQuestion1) {
                throw new ShopSystemException("问题一可能不存在了");
            }
            SafeQuestion safeQuestion3 = safeQuestionMapper.selectById(questionId2);
            if (null == safeQuestion3) {
                throw new ShopSystemException("问题二可能不存在了");
            }
            //判断用户是否已经设置过了
            QueryWrapper<UserQuestion> userQuestionQueryWrapper1 = new QueryWrapper<>();
            userQuestionQueryWrapper1.eq("uid", id).eq("sid", questionId1);
            UserQuestion userQuestion3 = userQuestionMapper.selectOne(userQuestionQueryWrapper1);
            if (null != userQuestion3) {
                throw new ShopSystemException("该用户问题一已经设置过了");
            }
            QueryWrapper<UserQuestion> userQuestionQueryWrapper2 = new QueryWrapper<>();
            userQuestionQueryWrapper2.eq("uid", id).eq("sid", questionId2);
            UserQuestion userQuestion4 = userQuestionMapper.selectOne(userQuestionQueryWrapper2);
            if (null != userQuestion4) {
                throw new ShopSystemException("该用户问题二已经设置过了");
            }
            //设置问题一
            UserQuestion userQuestion1 = new UserQuestion();
            userQuestion1.setSid(questionId1);
            userQuestion1.setUid(id);
            userQuestion1.setAnswer(answer1);
            Integer l = userQuestionMapper.insert(userQuestion1);
            if (l == 0) {
                throw new ShopSystemException("插入用户问题关系表失败");
            }
            //设置问题二
            UserQuestion userQuestion2 = new UserQuestion();
            userQuestion2.setSid(questionId2);
            userQuestion2.setUid(id);
            userQuestion2.setAnswer(answer2);
            Integer n = userQuestionMapper.insert(userQuestion2);
            if (n == 0) {
                throw new ShopSystemException("插入用户问题关系表失败");
            }
            result.setCode(201);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }

        return result;
    }

    /**
     * 获取所有省份
     *
     * @Author: 董星奇
     */
    @Override
    public List<Province> getAllProvinces() {

        List<Province> provinceList = null;
        try {
            QueryWrapper<Province> provinceQueryWrapper = new QueryWrapper<>();
            provinceQueryWrapper.isNotNull("id");
            provinceList = provinceMapper.selectList(provinceQueryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return provinceList;
    }

    /**
     * 获取选中省份的所有城市
     *
     * @Author: 董星奇
     */
    @Override
    public List<City> getCitiesByProvinceid(Integer provinceid) {
        List<City> cityList = null;
        try {
            QueryWrapper<City> cityQueryWrapper = new QueryWrapper<>();
            cityQueryWrapper.eq("provinceid", provinceid);
            cityList = cityMapper.selectList(cityQueryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cityList;
    }

    /**
     * 获取该城市下的所有区县
     *
     * @Author: 董星奇
     */
    @Override
    public List<Area> getAreasByCityid(Integer cityid) {
        List<Area> areaList = null;
        try {
            QueryWrapper<Area> areaQueryWrapper = new QueryWrapper<>();
            areaQueryWrapper.eq("cityid", cityid);
            areaList = areaMapper.selectList(areaQueryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return areaList;
    }

    /**
     * 用户新增收货地址
     *
     * @param receiverParam 收货地址实体类
     * @Author: 董星奇
     */
    @Override
    public Result addReceiverAddress(ReceiverParam receiverParam) {
        Result result = new Result();
        try {
            String token = receiverParam.getToken();
            String receiver = receiverParam.getReceiver();
            String phone = receiverParam.getPhone();
            String province = receiverParam.getProvince();
            String city = receiverParam.getCity();
            String area = receiverParam.getArea();
            String locations = receiverParam.getLocations();
            if (StringUtils.isBlank(token)) {
                throw new ShopSystemException("没有携带token信息");
            }
            if (StringUtils.isBlank(receiver)) {
                throw new ShopSystemException("收货人不能为空");
            }
            if (StringUtils.isBlank(phone)) {
                throw new ShopSystemException("手机号码不能为空");
            }
            if (StringUtils.isBlank(province)) {
                throw new ShopSystemException("省份不能为空");
            }
            if (StringUtils.isBlank(city)) {
                throw new ShopSystemException("城市不能为空");
            }
            if (StringUtils.isBlank(area)) {
                throw new ShopSystemException("区县不能为空");
            }
            if (StringUtils.isBlank(locations)) {
                throw new ShopSystemException("详细地址不能为空");
            }
            if (!phone.matches(AppConstant.PHONE_REGEXP)) {
                throw new ShopSystemException("请输入正确的手机号码格式");
            }
            //获取Claims
            Claims claims = jwtOperation.parseJwt(token);
            Object userClaim = claims.get("user");
            if (null == claims || null == userClaim) {
                throw new ShopSystemException("无效的Token");
            }
            //获取用户信息
            User user = JSON.parseObject(String.valueOf(claims.get("user")), User.class);
            String username = user.getUserName();
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("userName", username);
            User loginUser = userMapper.selectOne(userQueryWrapper);
            Integer uid = loginUser.getId();
            QueryWrapper<Address> addressQueryWrapper = new QueryWrapper<>();
            addressQueryWrapper.eq("receiver", receiver).eq("phone", phone).eq("province", province).eq("city", city).eq("area", area).eq("locations", locations).eq("uid", uid);
            Address address1 = addressMapper.selectOne(addressQueryWrapper);
            if (null != address1) {
                throw new ShopSystemException("你已经填写过该收货地址了");
            }
            Address address = new Address();
            address.setReceiver(receiver);
            address.setPhone(phone);
            address.setProvince(province);
            address.setCity(city);
            address.setArea(area);
            address.setLocations(locations);
            address.setUid(uid);
            Integer i = addressMapper.insert(address);
            if (i == 0) {
                throw new ShopSystemException("新增收货地址失败");
            }
            QueryWrapper<Address> addressQueryWrapper1 = new QueryWrapper<>();
            addressQueryWrapper1.eq("receiver", receiver).eq("phone", phone).eq("province", province).eq("city", city).eq("area", area).eq("locations", locations).eq("uid", uid);
            Address address2 = addressMapper.selectOne(addressQueryWrapper1);
            Integer aid = address2.getId();
            UserAddress userAddress = new UserAddress();
            userAddress.setAid(aid);
            userAddress.setUid(uid);
            userAddress.setStatus(AppConstant.NO_DEFAULT_ADDRESS);
            Integer n = userAddressMapper.insert(userAddress);
            if (n == 0) {
                throw new ShopSystemException("新增用户地址关系表失败");
            }
            result.setCode(201);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 获取当前用户的收货地址
     *
     * @param token token
     * @Author: 董星奇
     */
    @Transactional
    @Override
    public List<Address> getAllAddressesByUserId(String token) {
        List<Address> addressList = null;
        try {
            if (StringUtils.isBlank(token)) {
                throw new ShopSystemException("没有携带Token信息");
            }
            //获取Claims
            Claims claims = jwtOperation.parseJwt(token);
            Object userClaim = claims.get("user");
            if (null == claims || null == userClaim) {
                throw new ShopSystemException("无效的Token");
            }
            //获取用户信息
            User user = JSON.parseObject(String.valueOf(claims.get("user")), User.class);
            String username = user.getUserName();
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("userName", username);
            User loginUser = userMapper.selectOne(userQueryWrapper);
            Integer userid = loginUser.getId();
            QueryWrapper<Address> addressQueryWrapper = new QueryWrapper<>();
            addressQueryWrapper.eq("uid", userid);
            addressList = addressMapper.selectList(addressQueryWrapper);
        } catch (ShopSystemException e) {
            e.printStackTrace();
        }
        return addressList;
    }

    /**
     * 删除用户指定要删除的收货地址
     *
     * @param token     token
     * @param addressid 地址id
     * @Author 董星奇
     */
    @Transactional
    @Override
    public Integer delAddressById(String token, Integer addressid) {
        Integer count = 0;
        try {
            if (StringUtils.isBlank(token)) {
                throw new ShopSystemException("没有携带Token信息");
            }
            if (null == addressid) {
                throw new ShopSystemException("地址id不能为空");
            }
            //获取Claims
            Claims claims = jwtOperation.parseJwt(token);
            Object userClaim = claims.get("user");
            if (null == claims || null == userClaim) {
                throw new ShopSystemException("无效的Token");
            }
            //获取用户信息
            User user = JSON.parseObject(String.valueOf(claims.get("user")), User.class);
            String username = user.getUserName();
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("userName", username);
            User loginUser = userMapper.selectOne(userQueryWrapper);
            //当前用户Id
            Integer userid = loginUser.getId();
            Integer i = addressMapper.deleteById(addressid);
            if (i == 0) {
                throw new ShopSystemException("删除地址失败");
            }
            QueryWrapper<UserAddress> userAddressQueryWrapper = new QueryWrapper<>();
            userAddressQueryWrapper.eq("uid", userid).eq("aid", addressid);
            Integer m = userAddressMapper.delete(userAddressQueryWrapper);
            if (m == 0) {
                throw new ShopSystemException("删除用户地址关系表失败");
            }
            count++;
        } catch (ShopSystemException e) {
            e.printStackTrace();
        }
        return count;
    }

    /**
     * 设置用户指定的默认收货地址
     *
     * @param token     token
     * @param addressid 地址id
     * @Author: 董星奇
     */
    @Override
    public Integer setDefaultAddressById(String token, Integer addressid) {
        Integer count = 0;
        try {
            if (StringUtils.isBlank(token)) {
                throw new ShopSystemException("没有携带Token信息");
            }
            if (null == addressid) {
                throw new ShopSystemException("地址id不能为空");
            }
            //获取Claims
            Claims claims = jwtOperation.parseJwt(token);
            Object userClaim = claims.get("user");
            if (null == claims || null == userClaim) {
                throw new ShopSystemException("无效的Token");
            }
            //获取用户信息
            User user = JSON.parseObject(String.valueOf(claims.get("user")), User.class);
            String username = user.getUserName();
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("userName", username);
            User loginUser = userMapper.selectOne(userQueryWrapper);
            //当前用户Id
            Integer userid = loginUser.getId();
            QueryWrapper<UserAddress> userAddressQueryWrapper = new QueryWrapper<>();
            userAddressQueryWrapper.eq("status", AppConstant.USER_DEFAULT_ADDRESS_STATUS);
            UserAddress userAddress = userAddressMapper.selectOne(userAddressQueryWrapper);
            //用户已经设置了默认地址
            if (null != userAddress) {
                UserAddress userAddress1 = new UserAddress();
                userAddress1.setId(userAddress.getId());
                userAddress1.setStatus(AppConstant.NO_DEFAULT_ADDRESS);
                userAddressMapper.updateById(userAddress1);
            }
            //用户没有设置默认地址
            QueryWrapper<UserAddress> userAddressQueryWrapper1 = new QueryWrapper<>();
            userAddressQueryWrapper1.eq("uid", userid).eq("aid", addressid);
            UserAddress userAddress2 = userAddressMapper.selectOne(userAddressQueryWrapper1);
            userAddress2.setStatus(AppConstant.USER_DEFAULT_ADDRESS_STATUS);
            Integer i = userAddressMapper.updateById(userAddress2);
            if (i == 0) {
                throw new ShopSystemException("设置默认地址失败");
            }
            count++;
        } catch (ShopSystemException e) {
            e.printStackTrace();
        }
        return count;
    }

    /**
     * 用户编辑指定的地址
     *
     * @param updateReveiverParam 编辑地址实体类
     * @Author: 董星奇
     */
    @Override
    public Integer updateAddress(UpdateReveiverParam updateReveiverParam) {
        Integer count = 0;
        try {
            String token = updateReveiverParam.getToken();
            Integer addressid = updateReveiverParam.getAddressid();
            String receiver = updateReveiverParam.getReceiver();
            String phone = updateReveiverParam.getPhone();
            String province = updateReveiverParam.getProvince();
            String city = updateReveiverParam.getCity();
            String area = updateReveiverParam.getArea();
            String locations = updateReveiverParam.getLocations();
            if (StringUtils.isBlank(token)) {
                throw new ShopSystemException("没有携带Token信息");
            }
            if (null == addressid) {
                throw new ShopSystemException("不知道修改哪个地址");
            }
            if (StringUtils.isBlank(receiver)) {
                throw new ShopSystemException("收货人不能为空");
            }
            if (StringUtils.isBlank(phone)) {
                throw new ShopSystemException("手机号码不能为空");
            }
            if (StringUtils.isBlank(province)) {
                throw new ShopSystemException("填写省份不能为空");
            }
            if (StringUtils.isBlank(city)) {
                throw new ShopSystemException("填写城市不能为空");
            }
            if (StringUtils.isBlank(area)) {
                throw new ShopSystemException("填写区县不能为空");
            }
            if (StringUtils.isBlank(locations)) {
                throw new ShopSystemException("填写详细地址不能为空");
            }
            if (!phone.matches(AppConstant.PHONE_REGEXP)) {
                throw new ShopSystemException("请输入正确的手机号码格式");
            }
            //获取Claims
            Claims claims = jwtOperation.parseJwt(token);
            Object userClaim = claims.get("user");
            if (null == claims || null == userClaim) {
                throw new ShopSystemException("无效的Token");
            }
            //获取用户信息
            User user = JSON.parseObject(String.valueOf(claims.get("user")), User.class);
            String username = user.getUserName();
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("userName", username);
            User loginUser = userMapper.selectOne(userQueryWrapper);
            Integer userid = loginUser.getId();
            Address address = new Address();
            address.setId(addressid);
            address.setReceiver(receiver);
            address.setPhone(phone);
            address.setProvince(province);
            address.setCity(city);
            address.setArea(area);
            address.setLocations(locations);
            address.setUid(userid);
            Integer i = addressMapper.updateById(address);
            if (i == 0) {
                throw new ShopSystemException("编辑地址失败");
            }
            count++;
        } catch (ShopSystemException e) {
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public Result getUserRecords() {
        Result result = new Result();
        try {
            result.setData(userMapper.selectList(null));
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 通过用户名获取账户记录
     * @Author: 陈聪敏
     * @Date: 2020/3/16 0016 18:47
     */
    @Override
    public Result getUserRecordsByCondition(String keyword) {
        Result result = new Result();
        try{
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            if(!StringUtils.isBlank(keyword)){
                wrapper.eq("username",keyword);
            }
            List<User> users = userMapper.selectList(wrapper);
            result.setCode(200);
            result.setData(users);
        }catch (ShopSystemException e){
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 管理员给用户退款
     * @Author: 陈聪敏
     * @Date: 2020/3/16 0016 18:47
     */
    @Override
    public Result refund(Integer uid, BigDecimal money) {
        Result result = new Result();
        try{
            User newUser = new User();
            newUser.setId(uid);
            System.out.println(uid);
            User user = userMapper.selectById(uid);
            newUser.setBalance(user.getBalance()+money);
            userMapper.updateById(newUser);
            result.setCode(200);
        }catch (ShopSystemException e){
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 获取用户的收藏
     * @Author: 孙玮立
     * @Date: 2020/3/20  21:47
     */
    @Override
    public Result getUserCollections(String token) {
        Result result = new Result();
        try {
            User user = LoginUser(token);
            Integer id = user.getId();
            QueryWrapper<CollectionInfo> collectionInfoQueryWrapper = new QueryWrapper<>();
            collectionInfoQueryWrapper.eq("uid",id);
            List<CollectionInfo> collectionInfos = collectionMapper.selectList(collectionInfoQueryWrapper);
            List<UserCollections> userCollections = new ArrayList<>();
            for (CollectionInfo collectionInfo:collectionInfos){
                UserCollections userCollection = new UserCollections();
                Integer pid = collectionInfo.getPid();
                Product product = productMapper.selectById(pid);
                QueryWrapper<Evaluate> evaluateQueryWrapper = new QueryWrapper<>();
                evaluateQueryWrapper.eq("type",1);
                Integer good = evaluateMapper.selectCount(evaluateQueryWrapper);
                Integer count = evaluateMapper.selectCount(null);
                int praise = good / count;
                userCollection.setProduct(product);
                userCollection.setPraise(praise);
                userCollections.add(userCollection);

            }
            result.setData(userCollections);
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 获取用户的浏览记录
     * @Author: 孙玮立
     * @Date: 2020/3/20  21:47
     */
    @Override
    public Result getUserBrowse(String token) {
        Result result = new Result();
        try {
            UserBrowse userBrowse = new UserBrowse();
            User user = LoginUser(token);
            Integer id = user.getId();
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);
            QueryWrapper<History> historyQueryWrapper =new QueryWrapper<>();
            historyQueryWrapper.eq("uid",id);
            historyQueryWrapper.like("browsestime",format);
            List<History> histories = historyMapper.selectList(historyQueryWrapper);

            List<Product> nowBrowses = new ArrayList<>();
            List<Product> oldBrowses = new ArrayList<>();
            for (History history:histories){
                Integer pid = history.getPid();
                Product product = productMapper.selectById(pid);
                nowBrowses.add(product);
            }

            QueryWrapper<History> historyQueryWrapper1=new QueryWrapper<>();
            historyQueryWrapper1.eq("uid",id);
            historyQueryWrapper1.notLike("browsestime",format);
            List<History> histories1 = historyMapper.selectList(historyQueryWrapper1);
            for (History history1:histories1){
                Integer pid = history1.getPid();
                Product product = productMapper.selectById(pid);
                oldBrowses.add(product);
            }

            userBrowse.setNowBrowses(nowBrowses);
            userBrowse.setOldBrowses(oldBrowses);
            result.setData(userBrowse);
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: 根据用户id和商品id删除浏览记录
     * @Author: 孙玮立
     * @Date: 2020/3/20  21:47
     */
    @Override
    public Result delUserBrowse(String token, Integer id) {
        Result result = new Result();
        try {
            User user = LoginUser(token);
            Integer uid = user.getId();
            QueryWrapper<History> historyQueryWrapper = new QueryWrapper<>();
            historyQueryWrapper.eq("pid",id).eq("uid",uid);
            historyMapper.delete(historyQueryWrapper);
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }


    /**
     * @Description: 获取用户的评价记录
     * @Author: 孙玮立
     * @Date: 2020/3/20  21:47
     */
    @Override
    public Result getUserEvaluate(String token) {
        Result result = new Result();
        try {
            User user = LoginUser(token);
            Integer id = user.getId();
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("uid",id).eq("evaluatestatus",1);
            List<Order> orders = orderMapper.selectList(orderQueryWrapper);
            System.out.println("orders:"+orders);
            List<UserEvaluate> evaluates = new ArrayList<>();
            for (Order order:orders){
                Integer oid = order.getId();
                QueryWrapper<OrderProductRef> orderProductRefQueryWrapper = new QueryWrapper<>();
                orderProductRefQueryWrapper.eq("oid",oid);
                List<OrderProductRef> orderProductRefs = orderProductRefMapper.selectList(orderProductRefQueryWrapper);
                System.out.println("orderProductRefs:"+orderProductRefs);
                for (OrderProductRef orderProductRef : orderProductRefs){
                    UserEvaluate userEvaluate = new UserEvaluate();
                    Integer pid = orderProductRef.getPid();
                    Integer packid = orderProductRef.getPackid();
                    Integer fid = orderProductRef.getFid();
                    Product product = productMapper.selectById(pid);
                    Packaging packaging = packagingMapper.selectById(packid);
                    Flavor flavor = flavorMapper.selectById(fid);
                    QueryWrapper<Evaluate> evaluateQueryWrapper = new QueryWrapper<>();
                    evaluateQueryWrapper.eq("uid",user.getId()).eq("pid",pid);
                    Evaluate evaluate = evaluateMapper.selectOne(evaluateQueryWrapper);
                    System.out.println(evaluate);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date parse = sdf.parse(evaluate.getEvaluatetime());
                    userEvaluate.setData(String.valueOf(parse));
                    userEvaluate.setFlavor(flavor.getFlavor());
                    userEvaluate.setEvaluate(evaluate.getEvaluate());
                    userEvaluate.setPackaging(packaging.getPackaging());
                    userEvaluate.setProduct(product);
                    evaluates.add(userEvaluate);
                }

            }
            result.setData(evaluates);
            result.setCode(200);
        } catch (ShopSystemException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }
}
